/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.network;

import client.controller.events.VisitorCreatedEvent;
import client.controller.events.VisitorDeletedEvent;
import client.controller.events.VisitorGuideEvent;
import client.controller.events.VisitorListener;
import client.controller.events.VisitorUpdatedEvent;
import common.Config;
import common.model.Visitor;
import common.model.message.Message;
import java.net.*;
import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author nicolas
 */
public class NetworkClient {
    final Logger logger = LoggerFactory.getLogger(NetworkClient.class);
    private static final int PORT = Integer.parseInt(Config.getProperty().getProperty("client.hostport"));;     // server details
    private static final String HOST = Config.getProperty().getProperty("client.hostip");
    private Socket sock;
    private PrintWriter out;  // output to the server
    private String userName;
    private Visitor refToLocalVisitor;

    public NetworkClient(Visitor local) {
        this.userName = local.getUserName();
        this.refToLocalVisitor = local;

        makeContact();    // Make contact with server
    } // end of ChatClient();

    public Visitor getRefToLocalVisitor() {
        return refToLocalVisitor;
    }

    /** Close connection */
    public void closeLink() {
        try {
            out.println("bye");    // tell server that client is disconnecting
            sock.close();
        } catch (Exception e) {
            System.out.println(e);
        }

        System.exit(0);
    } // end of closeLink()

    /** Contact the server and start a chatWatcher thread */
    private void makeContact() // contact the server and start a ChatWatcher thread
    {
        try {
            sock = new Socket(HOST, PORT);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(sock.getOutputStream(), true);  // autoflush

            new NetworkWatcher(this, in, this.userName).start();    // start watching for server msgs
        } catch (Exception e) {
            logger.error(e.getMessage());
            //Could not connect to server -> exit
            System.exit(1);
        }
    }  // end of makeContact()

    /**
     * Be carefull !!! There is no content verification
     */
    public void sendMessage(String message) /* Check if the user has supplied a message, then
    send it to the server. */ {
        out.println(message);
    }  // end of sendMessage()

    public void sendMessage(Message msg) {
        out.println(msg.messageToString());
    }

}
